﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Text;
using SdmxMl.Helper;
using SdmxMl.Common;
using System.Data;
using SdmxMl.Manager;
namespace SdmxMl.Structure
{
    /// <summary>
    /// CategoryRefType references a category from within a category scheme.
    /// Reference fields are required for both the scheme and the item.
    /// </summary>
    public class CategoryRefType : ArtefactRefBase
    {
        #region Properties

        // Persisted as ID and the id property is persisted as maintainableParentID
        public string CategoryId { get; set; }
        

        public string TargetUrn
        {
            get
            {
                if (IsFilled == false)
                    return string.Empty;

                // create a category ghierarchy to express CategiriId
                string[] arrCat = CategoryId.Split('.');

                Category rootCat = new Category(null, null);
                rootCat.Id = arrCat[0];
                Category parentCat = rootCat;
                for (int i = 0; i < arrCat.Length; ++i)
                {
                    if (i > 0)
                    {
                        Category cat = new Category(null, parentCat);
                        cat.Id = arrCat[i];
                        parentCat = cat;
                   }
                }
                return UrnManager.FullIdToUrn(SdmxArtefactType.CategorySchemes, FullIdent, parentCat, null);
            }

            set
            {
                UrnParser p = new UrnParser(value);
                if (p.IsSupported && p.ArType == SdmxArtefactType.CategorySchemes && string.IsNullOrEmpty(p.SubType) == false)
                {
                    AgencyId = p.AgencyId;
                    Id = p.ArtefactId;
                    Version = p.Version;
                    CategoryId = p.SubTypeId;
                }
                else
                {
                    AgencyId = Id = Version = CategoryId = string.Empty;
                }

            }
        }
        #endregion

        public CategoryRefType()
        {
        }
        public CategoryRefType(XmlNode nodeTarget, SdmxNamespaceManager nsmgr)
        {
                  // Is source given via full Reference
            XmlNode ndRef = nodeTarget.SelectSingleNode("./Ref", nsmgr);
            if (ndRef != null)
            {
                Id = Xmlhelper.GetAtt(ndRef, "maintainableParentID");
                AgencyId = Xmlhelper.GetAtt(ndRef, "agencyID");
                CategoryId = Xmlhelper.GetAtt(ndRef, "id");
                Version = Xmlhelper.GetAtt(ndRef, "maintainableParentVersion");

                if (IsFilled == false)
                    throw new ApplicationException("Invalid Ref node (incomplete)");
            }
      }

    }
}
